package com.caishi.lkx.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.caishi.lkx.user.config.ThirdOauthConfig;
import com.zzw.common.exception.BizException;
import com.zzw.common.exception.BizRuntimeException;
import com.caishi.lkx.user.UserResultCode;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author huangpeng
 * @Description //carsi工具类
 * @Date 2023/8/24 13:56
 **/
@Component
@Slf4j
public class CarsiUtil {
    private static final String priKey = "MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCcjh+gOfLrdm4IOF0yuF3JyosrSjUyCAvQGj7Jpio9vim4ocP4UkdTOMksVsjd4XI9Yz5Ucpu9Q7O/1WSoo8sFlAmbfgFGr3Atb22l/Gvk/2T2SiJ4CEBab3PwJjlTHFwh7CKHoUwWC3MAAzvDtezO/O+MSkUN4NxFa1U2gz4jTGxTVbecLA3qbI07XjtYraNRdV2ULYOZzfY02iLA23lNlc/5KC8IyjOUJnFtfMrr91PPwa5hh+KkTGK8Ss2S99UbShUL/rGFa2No3NNt0DzDfXRKA7Pl4WWM7phGJebrnS0ansFtCfYVA/pAsEfo6lytoP+Y/Bn3LQvnx9vpTGlfkAJCpdCy8tG3kTR2Oy/aIpeuSNFsEkubM0ifm2jkGixkY93gdt3oqx+uxBRN6JB625iZfIqdu3JfZuJYGpGlU/7CBXOmxVWYfGe+H8B1Kbje1z/RbUAilHyUoxNyEYQWH4k+jfiTOcDs9fFpkIMEokIZ6PQozzyIT2u2t3Y8h/CAqHDyRm/P0McNb7bxjF5p0kZ87nv4cuO43rVkTcUstGXv3C3PYdf9v5e7ONfWk3GC95S6GqmjUHdYLWedMrvR46D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+6H2edFqZH2NmnKS2eYGSTMCAwEAAQ==";
    private static final RSA rsa;
    private static ThirdOauthConfig thirdOauthConfig;

    @Resource
    public void setThirdOauthConfig(ThirdOauthConfig thirdOauthConfig) {
        CarsiUtil.thirdOauthConfig = thirdOauthConfig;

    }

    static {
        rsa = new RSA(priKey, pubKey);

    }

    public static Map<String, String> decrypt(String code) throws BizException {
        if (StrUtil.isBlank(code)) {
            throw new BizRuntimeException(UserResultCode.thirdLoginCodeFail);
        }
        String carsiClientId = thirdOauthConfig.getCarsiClientId();
        String carsiClientSecret = thirdOauthConfig.getCarsiClientSecret();
        String carsiTokenUrl = thirdOauthConfig.getCarsiTokenUrl();
        Map<String, Object> body = MapUtil.<String, Object>builder()
                .put("grant_type", "authorization_code")
                .put("client_id", carsiClientId)
                .put("client_secret", carsiClientSecret)
                .put("code", code).build();
        String resp = HttpUtil.post(carsiTokenUrl, body);
        JSONObject accessTokenMap = JSONObject.parseObject(resp);
        String accessToken = accessTokenMap.get("access_token").toString();
        if (StrUtil.isBlank(accessToken)) {
            throw new BizException(UserResultCode.accesstokenFail);
        }
        String carsiResourceUrl = thirdOauthConfig.getCarsiResourceUrl();
        String url = String.format(carsiResourceUrl, accessToken, carsiClientId);
        JSONObject userInfo = JSONObject.parseObject(HttpUtil.get(url));
        String uid = userInfo.get("carsi-persistent-uid").toString();
        String affiliation = userInfo.get("carsi-affiliation").toString();
        byte[] uidByte = rsa.decrypt(Base64.decode(uid.getBytes(StandardCharsets.UTF_8)), KeyType.PrivateKey);
        byte[] affiliationByte = rsa.decrypt(Base64.decode(affiliation.getBytes(StandardCharsets.UTF_8)), KeyType.PrivateKey);
        uid = new String(uidByte);
        affiliation = new String(affiliationByte);
        return MapUtil.<String, String>builder().put("uid", uid).put("affiliation", affiliation).build();
    }

    public static String getAffiliation(String code) {
        try {
            Map<String, String> decrypt = decrypt(code);
            return decrypt.get("affiliation");
        } catch (Exception e) {
            log.error("caris get affiliation error:", e);

        }
        return null;
    }

    public static String getUid(String code) throws BizException {
        try {
            Map<String, String> decrypt = decrypt(code);
            return decrypt.get("uid");
        } catch (Exception e) {
            log.error("caris get uid error:", e);

        }
        return null;

    }
}
